'use strict';

/**
 * @ngdoc directive
 * @name App.directive:uiToggleClass
 * @description
 * # uiToggleClass
 */
angular.module('App')
  .directive('uiToggleClass', function () {
    return {
      restrict: 'AC',
      link: function (scope, el, attr) {
        el.on('click', function (e) {
          e.preventDefault();
          $(el).toggleClass('active');
          var classes = attr.uiToggleClass.split(','), targets = (attr.target && attr.target.split(',')) || Array(el);
          angular.forEach(classes, function (_class, key) {
            var target = targets[key];
            ( _class.indexOf('*') !== -1 ) && magic(_class, target);
            $(target).toggleClass(_class);
          });
        });

        function magic(_class, target) {
          var patt = new RegExp('\\s' +
            _class.
              replace(/\*/g, '[A-Za-z0-9-_]+').
              split(' ').
              join('\\s|\\s') +
            '\\s', 'g');

          var cn = ' ' + $(target)[0].className + ' ';
          while (patt.test(cn)) {
            cn = cn.replace(patt, ' ');
          }
          $(target)[0].className = $.trim(cn);
        }
      }
    };
  });
